#include "register.h"
#include "ui_register.h"
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QCryptographicHash>
#include <QUdpSocket>
#include <QHostAddress>

Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);

    // 初始化UDP套接字
    udpSocket = new QUdpSocket(this);


    // 信号连接
    connect(ui->pushButton, &QPushButton::clicked, this, &Register::on_pushButton_clicked);
    connect(udpSocket, &QUdpSocket::readyRead, this, &Register::handleServerResponse);
}

Register::~Register()
{
    delete ui;
}

void Register::on_pushButton_clicked()
{
    QString username = ui->lineEdit->text().trimmed();
    QString password = ui->lineEdit_2->text();
    QString confirm = ui->lineEdit_3->text();

    // 验证输入
    if(username.isEmpty()){
        QMessageBox::warning(this, "错误", "用户名不能为空");
        return;
    }
    if(password.isEmpty()){
        QMessageBox::warning(this, "错误", "密码不能为空");
        return;
    }
    if(password != confirm){
        QMessageBox::warning(this, "错误", "两次输入的密码不一致");
        return;
    }

    // 密码加密
    QString SALT = "diwu";
    QString encrypted = md5Hash(password + SALT);

    // 构建注册请求
    QString request = "R " + username + " " + encrypted;

    // 发送给服务器
    udpSocket->writeDatagram(request.toUtf8(),
                           QHostAddress("192.168.54.46"), // 服务器IP
                           6666); // 服务器端口
    // 客户端发送后
    qDebug() << "已发送注册请求到服务器:" << request;
}

QString Register::md5Hash(const QString &data)
{
    QByteArray hash = QCryptographicHash::hash(
        data.toUtf8(),
        QCryptographicHash::Md5
    );
    return QString(hash.toHex());
}

void Register::handleServerResponse()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray response;
        response.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(response.data(), response.size(), &sender, &senderPort);


        if (response == "ROK") {
            QMessageBox::information(this, "成功", "注册成功");
            this->close();
        } else {
            QMessageBox::critical(this, "错误", "注册失败: " + response);
        }
    }
}
